--
-- Author: shunguo.chen
-- Date: 2019-07-08 17:06:36
--
-- TeamTargetPanel 队伍目标panel
--

local IconRender = require("app.widget.renders.IconRender")

local TeamMatchMemberPanel = import(".TeamMatchMemberPanel")
local TeamMatchListPanel = import(".TeamMatchListPanel")
local TeamMatchCrossPanel = import(".TeamMatchCrossPanel")

local ClassRef = app.mvc.createPanelClass(...)

local ACTIVITY_ITEM_STRS = {
    L("ashes_trophy_gold"),
    L("ashes_trophy_silver"),
    L("ashes_trophy_bronze")
}

local MATCH_COMBAT_STR = L("team_text2")

local SINGLE_START_STR = L("lua_code_text_538")
local TRAINING_START_STR = L("lua_code_text_513")
local TEAM_START_STR = L("lua_code_text_61")
local GOTO_START_STR = L("lua_code_text_484")
local CREATE_TEAM_STR = L("lua_code_text_157")
local RECV_TASK_STR = L("lua_code_text_186")
local CROSS_MATCH_STR = L("teamTargetQuickMatch1")
local CROSS_CANCEL_MATCH_STR = L("lua_code_text_110")

--data = TeamTargetVo
function ClassRef.createWithData(data, node)
    local sprite = ClassRef.extend(node)
    if node == nil then
        ccui.Helper:doLayout(sprite)
    end
    sprite:init(data)
    return sprite
end
function ClassRef.create(node)
    return ClassRef.createWithData(nil, node)
end

function ClassRef:getGuideNodeFunc(id)
    if id == 400 then
        if self._tipsBtn:isVisible() then
            return self._tipsBtn
        end
    elseif id == 410 or id == 430 then
        if self._matchBtn:isVisible() then
            return self._matchBtn
        end
    end
end

function ClassRef:remove()
    self._teamListPanel:remove()
end

--
function ClassRef:init(data)
    self.super.init(self, data)

    self._timeline = self:getTimeline()

    self._memberPanel = TeamMatchMemberPanel.create(self._ui.Panel_team)
    self._teamListPanel = TeamMatchListPanel.create(self._ui.Panel_tuijian)
    self._crossPanel = TeamMatchCrossPanel.create(self._ui.node_match)

    -- top --
    local topPanel = self._ui.Panel_top
    self._autoBtnText = topPanel:getChildByName("selected_tlt")
    self._autoBtn = topPanel:getChildByName("selected_btn")
    self._autoBtn:addClickEventListener(handler(self, self._onClickAutoBtn))

    self._icon = topPanel:getChildByName("icon")
    self._nameText = topPanel:getChildByName("name")
    self._descText = topPanel:getChildByName("desc")
    self._numIcon = topPanel:getChildByName("num_icon")
    self._numText = topPanel:getChildByName("num_text")
    self._combatText = topPanel:getChildByName("combat_text")
    self._tipText = topPanel:getChildByName("tip_text")
    self._tipLeftText = topPanel:getChildByName("tip_text_left")

    self._topNormalPanel = topPanel:getChildByName("Panel_1")
    self._topNormalBg = self._topNormalPanel:getChildByName("bg02")
    self._topNormalBgSize = self._topNormalBg:getContentSize()
    self._topSpeedPanel = topPanel:getChildByName("Panel_2")
    self._rankBtn = topPanel:getChildByName("rank_btn")
    self._rankBtn:addClickEventListener(function()
        executeFunc(self._onOperate, "openRank", self._data)
    end)

    self._timeTip = topPanel:getChildByName("tips_time")
    self._timeText = self._timeTip:getChildByName("text")

    local bomPanel = self._ui.Panel_bom
    self._tipsBtn = bomPanel:findChild("Button_tips/Panel_1")
    display.uiAddClick(self._tipsBtn, function()
        executeFunc(self._onOperate, "openBook", self._data)
    end, true)

    self._matchTips = bomPanel:getChildByName("tips")
    display.setCascadeOpacityEnabled(self._matchTips, true)
    self._matchTipText = self._matchTips:getChildByName("tlt")
    self._matchBtn = bomPanel:getChildByName("Button_found")
    self._matchBtnText = self._matchBtn:getChildByName("name")
    self._matchBtn:addClickEventListener(handler(self, self._onClickMatchBtn))

    self._enterBtn = bomPanel:getChildByName("Button_enter")
    self._enterBtnText = self._enterBtn:getChildByName("name")
    self._enterBtn:addClickEventListener(handler(self, self._onEnterBtnClick))

    self._rewardText = bomPanel:getChildByName("Text")

    local itemPanel = bomPanel:getChildByName("Panel_icon")
    local itemRenders = {0,0,0,0,0}
    local itemTexts = {0,0,0,0,0}
    for i=1,5 do
        local render = IconRender.create(itemPanel:getChildByName("icon" .. i))
        render:setTipEnable(true)
        render:setTipUnShowOrigin(true)
        itemRenders[i] = render
        itemTexts[i] = itemPanel:getChildByName("Text_" .. i)
    end
    self._bomItemPanel = itemPanel
    self._itemTip = itemPanel:getChildByName("icon_text")
    self._itemRenders = itemRenders
    self._itemTexts = itemTexts

    self._itemTextColorGold = self._itemTexts[1]:getTextColor()
    self._itemTextColorGreen = self._itemTexts[2]:getTextColor()
    self._itemTextColorBlue = self._itemTexts[3]:getTextColor()

    self._bomSpeedPanel = bomPanel:getChildByName("Panel_rank")
    self._rankText = self._bomSpeedPanel:getChildByName("Text_rank")
    self._rankIcon = self._bomSpeedPanel:getChildByName("Image_rank")

end

function ClassRef:onOperate(cb)
    self.super.onOperate(self, cb)

    self._memberPanel:onOperate(cb)
    self._teamListPanel:onOperate(cb)
end

function ClassRef:_playAction()
    self._timeline:gotoFrameAndPlay(0, false)
end

function ClassRef:_pauseAction()
    self._timeline:gotoFrameAndPause(0)
end

function ClassRef:_onClickAutoBtn()
    local isBright = self._autoBtn:isBright()
    self._autoBtn:setBright(not isBright)
    if self._team then
        executeFunc(self._onOperate, "autoRecruit", self._data, isBright)
    else
        executeFunc(self._onOperate, "autoApply", self._data, isBright)
    end
end

function ClassRef:_onClickMatchBtn()
    -- 按钮保护0.5s不能点击
    self._matchBtn:setTouchEnabled(false)
    self._matchBtn:stopAllActions()
    self._matchBtn:performWithDelay(function()
        self._matchBtn:setTouchEnabled(true)
    end, 0.5)

    if self._data:isInCrossMatch() then
        executeFunc(self._onOperate, "cancelMatch", self._data)
        return
    end

    local hasTeam = self._team ~= nil
    local needAverageCombat = self._data:getAverageCombat()
    if needAverageCombat > 0 then
        local hasAverageCombat = UD:getCombatPower()
        if hasTeam then
            hasAverageCombat = self._team:getTeamAverageCapacity()
        end

        -- 战力不满足，播放动画
        if hasAverageCombat < needAverageCombat then
            self:_playAction()
            return
        end
    end

    if hasTeam then
        executeFunc(self._onOperate, "teamMatch", self._data)
    else
        executeFunc(self._onOperate, "singleMatch", self._data)
    end
end

-- 进入按钮点击，根据文本内容有不同的操作
function ClassRef:_onEnterBtnClick()
    local hasTeam = self._team ~= nil
    local btnStr = self._enterBtnText:getString()
    if btnStr == CREATE_TEAM_STR then
        executeFunc(self._onOperate, "createTeam", self._data)
    elseif btnStr == SINGLE_START_STR then
        if self._team then
            executeFunc(self._onOperate, "teamStart", self._data)
        else
            executeFunc(self._onOperate, "singleStart", self._data)
        end
    elseif btnStr == TEAM_START_STR then
        executeFunc(self._onOperate, "teamStart", self._data)
    elseif btnStr == TRAINING_START_STR then
        executeFunc(self._onOperate, "gotoTraining", self._data)
    elseif btnStr == GOTO_START_STR then
        executeFunc(self._onOperate, "gotoWorldBoss")
    elseif btnStr == RECV_TASK_STR then
        executeFunc(self._onOperate, "getGrayBattleTask")
    elseif btnStr == CROSS_MATCH_STR then
        executeFunc(self._onOperate, "singleMatch", self._data)
    elseif btnStr == CROSS_CANCEL_MATCH_STR then
        executeFunc(self._onOperate, "cancelMatch", self._data)
    end
end

-- data = TeamTargetVo
function ClassRef:refresh()
    local target = self._data

    self._matchBtn:stopAllActions()
    display.setBtnTouchEnable(self._matchBtn, true)

    local isSpeed = target:isSpeed()
    local isPvp = target:isPvp()
    local hasRank = target:getRank() ~= nil

    self._descText:setString(target:getDesc())
    self._icon:loadTexture(target:getIcon())
    self._rankBtn:setVisible(hasRank)

    -- 数值类型 pvp 需要特殊处理一下
    self._numIcon:setVisible(not isPvp)
    self._combatText:setVisible(not isPvp)
    if isPvp then
        self._nameText:setString(string.format(L("challengeTips8"), target:getNameWithDiff()))
        self._numText:setPositionX(self._numIcon:getPositionX())
        self._numText:setString(target:getRankStr())
    else
        self._nameText:setString(target:getNameWithDiff())
        self._numIcon:loadTexture(target:getNumTypeIcon(), 1)
        self._numText:setString(target:getNumTypeDesc())
        local combat = target:getCombat()
        self._combatText:setVisible(combat > 0)
        if combat > 0 then
            self._combatText:setString(combat)
            display.setNodesLeft(nil, self._numText, self._combatText)
        end
    end

    self._topSpeedPanel:setVisible(isSpeed)
    self._topNormalPanel:setVisible(not isSpeed)
    self._bomSpeedPanel:setVisible(isSpeed)
    self._bomItemPanel:setVisible(not isSpeed)

    self._rewardText:setVisible(true)
    self._rewardText:setString(isSpeed and L("lua_code_text_175") or L("lua_code_text_143"))

    -- 活动必定会有
    if not target:isActivity() then
        for i,text in ipairs(self._itemTexts) do
            text:setVisible(false)
        end
    end
    
    local tipStr, tipLeftStr
    if not self._tipsBtn:isVisible() then
        self._tipsBtn:setVisible(true)
    end

    if target:isPvp() then
        local pvpRewards = target:getRewards()

        for i,text in ipairs(self._itemTexts) do
            if i == 1 then
                text:setVisible(true)
                text:setString(isFirstWin and L("lua_code_text_122") or L("lua_code_text_123"))
            elseif isBoost then
                text:setVisible(true)
                text:setString(L("lua_code_text_505"))
                text:setTextColor(self._itemTextColorGreen)
            end
        end

        for i,render in ipairs(self._itemRenders) do
            local reward = pvpRewards[i]
            render:setVisible(reward ~= nil)
            if reward then
                render:setData(reward.item)

                local text = self._itemTexts[i]
                local color
                if reward.colorId == "gold" then
                    color = self._itemTextColorGold
                elseif reward.colorId == "green" then
                    color = self._itemTextColorGreen
                else
                    color = self._itemTextColorBlue
                end
                text:setVisible(true)
                text:setString(reward.name)
                text:setTextColor(color)
            end
        end
    elseif target:isActivity() then
        if target:isRewardNumLimit() then
            tipStr = string.format(L("lua_code_text_290"), target:getRestRewardNum(), target:getRewardNum())
        end

        local rewards = target:getRewards()
        if #rewards > 0 then
            for i,render in ipairs(self._itemRenders) do
                local reward = rewards[i]
                render:setVisible(reward ~= nil)
                if reward then
                    render:setData(reward)

                    local text = self._itemTexts[i]
                    local textStr = ACTIVITY_ITEM_STRS[i]
                    if textStr then
                        text:setVisible(true)
                        text:setString(textStr)
                        text:setTextColor(self._itemTextColorGold)
                    end
                end
            end
        else
            -- 一个奖励也没有，隐藏奖励面板和文本、查看按钮
            self._bomItemPanel:setVisible(false)
            self._rewardText:setVisible(false)
            self._tipsBtn:setVisible(false)
        end
    elseif target:isSpeed() then
        local speedInfo = target:getSpeedInfo()
        local bestRecord = speedInfo:getBestRecord()
        self._rankText:setString(TimeUtil.secondsToTime(bestRecord))
        self._rankIcon:loadTexture(speedInfo:getRankIcon(), 1)
        display.setNodesLeft(nil, self._rankText, self._rankIcon)
    else
        -- 其他副本最多只显示五个奖励
        local rewards = target:getRewards()
        for i,render in ipairs(self._itemRenders) do
            local reward = rewards[i]
            local isVisible = reward ~= nil and i <= 5
            render:setVisible(isVisible)
            if isVisible then
                -- 如果是地下城点数，显示上面的文字
                if reward.itemBagType == Enums.ItemBagType.daibi and
                    reward.tid == Enums.lootType.dungeonPoint then
                    self._itemTexts[i]:setVisible(true)
                    self._itemTexts[i]:setString(L("team_text16"))
                end
                render:setData(reward)
            end
        end

        if not target:isLowTarget() then
            -- 有每周次数限制
            local numLimit = target:isRewardNumLimit()
            local weeklyNumLimit = target:isWeeklyRewardNumLimit()
            if numLimit and weeklyNumLimit then
                tipLeftStr = string.format(L("team_text18"), target:getRestRewardNum(), target:getRewardNum())
                tipStr = string.format(L("team_text17"), target:getWeeklyRestRewardNum(), target:getWeeklyRewardNum())
            elseif numLimit and not weeklyNumLimit then
                tipStr = string.format(L("team_text18"), target:getRestRewardNum(), target:getRewardNum())
            elseif not numLimit and weeklyNumLimit then
                tipStr = string.format(L("team_text17"), target:getWeeklyRestRewardNum(), target:getWeeklyRewardNum())
            end
        end
    end

    -- 低级副本显示
    self._itemTip:setVisible(target:isLowTarget())

    self._tipText:setVisible(tipStr ~= nil)
    self._tipLeftText:setVisible(tipLeftStr ~= nil)
    if tipStr then
        if tipLeftStr then
            self._tipLeftText:setString(tipLeftStr)
        end
        self._tipText:setString(tipStr)
    end

    -- 非竞速下，根据师傅有tips或者有排行榜，调整self._topNormalBg的size
    if not isSpeed then
        if tipStr or hasRank then
            self._topNormalBg:setContentSize(self._topNormalBgSize)
        else
            local nameTextSize = self._nameText:getVirtualRendererSize()
            local size = cc.size(nameTextSize.width + 40, self._topNormalBgSize.height)
            self._topNormalBg:setContentSize(size)
        end
    end
    
    -- 显示开启时间显示
    local isTimeOpen, gap = target:checkTimeOpen()
    self._refreshGap = gap or 0
    self._isTimeOpen = isTimeOpen
    self:_refreshTime()

    self._memberPanel:refreshTarget(target)
    self._teamListPanel:refreshTarget(target)
    executeFunc(self._onOperate, "selectTarget", target)
end

-- 刷新限制的目标
function ClassRef:_refreshTime()
    self._timeTip:stopAllActions()

    if self._refreshGap <= 0 then
        self._timeTip:setVisible(false)
    else
        self._timeTip:setVisible(true)
        local str = self._isTimeOpen and L("lua_code_text_108") or L("lua_code_text_154")
        local _, timeStr = TimeUtil.secondsToStr(self._refreshGap, 1)
        self._timeText:setString(string.format(str, timeStr))
        self._timeTip:performWithDelay(function()
            self._refreshGap = self._refreshGap - 1
            if self._refreshGap <= 0 then
                local isTimeOpen, gap = self._data:checkTimeOpen()
                self._refreshGap = gap or 0
                self._isTimeOpen = isTimeOpen
            end
            self:_refreshTime()
        end, 1)
    end
end

function ClassRef:updateAutoApplyStatus()
    self._autoBtn:setBright(not self._data:isAutoApply())
end

function ClassRef:updateAutoRecruitStatus()
    self._autoBtn:setBright(not self._data:isAutoRecruit())
end

function ClassRef:refreshApplyNew(b)
    self._memberPanel:refreshApplyNew(b)
end

function ClassRef:refreshMember()
   self._memberPanel:setData(self._team)
end

function ClassRef:refreshTeamList(teamList)
    self._teamListPanel:setData(teamList)
end

-- 刷新推荐队伍的申请状态
function ClassRef:refreshTeamListApply(team)
    self._teamListPanel:refreshTeamApply(team)
end

function ClassRef:refreshTeam(team)
    self._team = team

    local hasTeam = team ~= nil
    local target = self._data
    local isPvp = target:isPvp()
    local isSingle = target:isSingle()
    local targetId = target.id
    local isInCrossMatch = target:isInCrossMatch()

    -- print("isInCrossMatch", isInCrossMatch, targetId)

    if isInCrossMatch then
        self._crossPanel:show()
        self._memberPanel:setVisible(false)
        self._teamListPanel:setVisible(false)

        self._crossPanel:setData(team)
    else
        self._crossPanel:hide()
        if team then
            self._memberPanel:setVisible(true)
            self._teamListPanel:setVisible(false)

            self:refreshMember()
            self:refreshApplyNew()
        else
            self._memberPanel:setVisible(false)
            self._teamListPanel:setVisible(true)
        end
    end

    local isAuto
    if team then
        isAuto = team:isAutoRecruit(targetId)
    else
        isAuto = target:isAutoApply()
    end

    -- print("isAuto, hasTeam, isSingle, targetId", isAuto, hasTeam, isSingle, targetId)

    local isOpen = target:isOpen()
    if not isOpen then
        self._matchBtn:setVisible(false)
        self._matchTips:setVisible(false)
        self._enterBtn:setVisible(false)
        self._autoBtn:setVisible(false)
        self._autoBtnText:setVisible(false)
        return
    end

    local btnStr
    local normalIconPath = Res.commonUIPath .. "team_btn_play_n.png"
    local pressIconPath = Res.commonUIPath .. "team_btn_play_p.png"
    if isSingle then
        -- 单人玩法 没有组队相关的东西，按钮有特殊背景
        self._autoBtn:setVisible(false)
        self._autoBtnText:setVisible(false)

        self._matchBtn:setVisible(false)
        self._matchTips:setVisible(false)

        if target:isTraining() then
            btnStr = TRAINING_START_STR
        elseif isPvp then
            btnStr = isInCrossMatch and CROSS_CANCEL_MATCH_STR or CROSS_MATCH_STR
        else
            btnStr = SINGLE_START_STR
        end
        normalIconPath = Res.commonUIPath .. "team_btn_playgreen_n.png"
        pressIconPath = Res.commonUIPath .. "team_btn_playgreen_p.png"
    else
        -- 可以快速匹配（跨服匹配） 显示匹配按钮
        local isQuickMatch = target:isQuickMatch()
        self._matchBtn:setVisible(isQuickMatch)
        self._matchTips:setVisible(isQuickMatch)
        if isQuickMatch then
            local matchBtnStr = isInCrossMatch and CROSS_CANCEL_MATCH_STR or CROSS_MATCH_STR
            self._matchBtnText:setString(matchBtnStr)
            local needCombat = target:getAverageCombat()
            self:_pauseAction()
            self._matchTipText:setString(string.format(MATCH_COMBAT_STR, needCombat))
        end

        local isShowAuto = true
        if hasTeam then
            -- 队员不能显示自动按钮
            isShowAuto = team:isMyTeam() and not isPvp
            if target:isWorldBoss() then
                -- 世界boss有队伍时，按钮文本为【前往挑战】
                btnStr = GOTO_START_STR
            else
                btnStr = TEAM_START_STR
            end
        else
            isShowAuto = not isPvp
            btnStr = CREATE_TEAM_STR
        end

        self._autoBtn:setVisible(isShowAuto)
        self._autoBtnText:setVisible(isShowAuto)
        if isShowAuto then
            self._autoBtnText:setString(team and L("lua_code_text_393") or L("lua_code_text_167"))
            self._autoBtn:setBright(not isAuto)
        end

        -- 灰烬入侵有特殊的按钮背景，未接受任务时，按钮文本为【接受任务】
        if target:isGrayBattle() then
            normalIconPath = Res.commonUIPath .. "team_btn_playorg_n.png"
            pressIconPath = Res.commonUIPath .. "team_btn_playorg_p.png"

            if not UD:hasGrayBattleInfo() then
                btnStr = RECV_TASK_STR
            end

            -- 灰烬入侵单人挑战不显示
            self._matchBtn:setVisible(false)
        end
    end

    -- 野外boss只组队
    if target:isWildBoss() and hasTeam then
        self._enterBtn:setVisible(false)
    else
        self._enterBtn:setVisible(true)
        self._enterBtn:loadTextureNormal( normalIconPath, 1 )
        self._enterBtn:loadTexturePressed( pressIconPath, 1 )
        self._enterBtnText:setString(btnStr)
    end
end

return ClassRef
